package com.fsnbigdata.web;
import com.fsnbigdata.domain.Ecosystem;
import com.fsnbigdata.enums.ResultEnum;
import com.fsnbigdata.exception.ParamException;
import com.fsnbigdata.util.ReflectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.roo.addon.web.mvc.controller.annotations.ControllerType;
import org.springframework.roo.addon.web.mvc.controller.annotations.RooController;
import org.springframework.roo.addon.web.mvc.controller.annotations.responses.json.RooJSON;
import com.fsnbigdata.service.api.EcosystemService;
import io.springlets.web.NotFoundException;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.util.UriComponents;
import springfox.documentation.annotations.ApiIgnore;

import java.lang.reflect.Method;

/**
 * = EcosystemsItemJsonController
 *
 * TODO Auto-generated class documentation
 *
 */
@RooController(entity = Ecosystem.class, pathPrefix = "/api", type = ControllerType.ITEM)
@RooJSON
@RestController
@RequestMapping(value = "/api/ecosystems/{id}", name = "EcosystemsItemJsonController", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = "Ecosystem", description = "生态环境" )
public class EcosystemsItemJsonController {

    /**
     * TODO Auto-generated attribute documentation
     *
     */
    private EcosystemService ecosystemService;

    /**
     * TODO Auto-generated constructor documentation
     *
     * @param ecosystemService
     */
    @Autowired
    public EcosystemsItemJsonController(EcosystemService ecosystemService) {
        this.ecosystemService = ecosystemService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @return EcosystemService
     */
    public EcosystemService getEcosystemService() {
        return ecosystemService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param ecosystemService
     */
    public void setEcosystemService(EcosystemService ecosystemService) {
        this.ecosystemService = ecosystemService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param id
     * @return Ecosystem
     */
    @ModelAttribute
    public Ecosystem getEcosystem(@PathVariable("id") Long id) {
        Ecosystem ecosystem = ecosystemService.findOne(id);
        if (ecosystem == null) {
            throw new NotFoundException(String.format("Ecosystem with identifier '%s' not found", id));
        }
        return ecosystem;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param ecosystem
     * @return ResponseEntity
     */
    @GetMapping(name = "show")
    //@PreAuthorize("hasRole('USER')")
    public ResponseEntity<?> show(@ApiIgnore @ModelAttribute Ecosystem ecosystem) {
        return ResponseEntity.ok(ecosystem);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param ecosystem
     * @return UriComponents
     */
    public static UriComponents showURI(Ecosystem ecosystem) {
        return MvcUriComponentsBuilder.fromMethodCall(MvcUriComponentsBuilder.on(EcosystemsItemJsonController.class).show(ecosystem)).buildAndExpand(ecosystem.getId()).encode();
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param storedEcosystem
     * @param ecosystem
     * @param result
     * @return ResponseEntity
     */
    @PutMapping(name = "update")
    @PreAuthorize("hasRole('DB_ECOSYSTEM')")
    @ApiOperation(value = "",notes = "update")
    public ResponseEntity<?> update(@ApiIgnore @ModelAttribute Ecosystem storedEcosystem, @Valid @RequestBody Ecosystem ecosystem, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new ParamException(ResultEnum.PARAM_ERROR.getCode(),
                    result.getFieldError().getDefaultMessage());
        }

        ecosystem.getImages().forEach(it -> it.setEcosystem(ecosystem));

        ecosystem.setId(storedEcosystem.getId());
        String name = getEcosystemService().findOne(storedEcosystem.getId()).getName();
        Ecosystem newEcosystem = getEcosystemService().save(ecosystem);
        Class<?> clazz = EcosystemsItemJsonController.class;
        Method method = clazz.getMethod("update", ReflectUtil.getPeremeterClass(clazz, "update"));
        ReflectUtil.setAnnotationOn(method,"更新生态库，名称："+name);

        return ResponseEntity.ok(newEcosystem);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param ecosystem
     * @return ResponseEntity
     */
    @DeleteMapping(name = "delete")
    @PreAuthorize("hasRole('DB_ECOSYSTEM')")
    @ApiOperation(value = "",notes = "delete")
    public ResponseEntity<?> delete(@ApiIgnore @ModelAttribute Ecosystem ecosystem) throws Exception {
        getEcosystemService().delete(ecosystem);
        Class<?> clazz = EcosystemsItemJsonController.class;
        Method method = clazz.getMethod("delete", ReflectUtil.getPeremeterClass(clazz, "delete"));
        ReflectUtil.setAnnotationOn(method,"删除生态库，名称："+ecosystem.getName());
        return ResponseEntity.ok().build();
    }
}
